<?php
/**
 * @package LaravelBoot
 *
 * @internal
 *
 * @author mawenpei
 * @date 2019/3/18 14:47
 * @version
 */
namespace Modules\Service\Logic;

use App\Models\Advs;
use App\Models\Banner;
use App\Models\Coupon;
use App\Models\Draw;
use App\Models\ErrorLog;
use App\Models\Feedback;
use App\Models\JrttEquipment;
use App\Models\LoginLog;
use App\Models\RechargeOrder;
use App\Models\RechargeOrderDetail;
use App\Models\RechargeTask;
use App\Models\Team;
use App\Models\User;
use App\Models\UserCar;
use App\Models\UserCoupon;
use App\Sms;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\Token\Token;
use App\Models\Configure;

class UserLogic extends BaseLogic
{
    //用户注册
    public static function userRegister(User $user){
        //生成随机码
        $openCode = User::randOpenCode();

        //获取新人专属优惠券

        try{
            //开启事务
            DB::beginTransaction();
            //注册
            $user->open_code = $openCode;
            $user->save();

            UserCoupon::sendRegisterCoupon($user->id);

            if ($user->parent_id){
                //给上级赠送抽奖机会
//                $drawData = Draw::where("user_id",$user->parent_id)->first();
//                if ($drawData){
//                    $drawData->num = $drawData->num+1;
//                }else{
//                    $draw = new Draw();
//                    $draw->user_id = $user->parent_id;
//                    $draw->num = 1;
//                    $draw->save();
//                }

                //给上级发优惠券
                UserCoupon::sendParentRegisterCoupon($user->parent_id);

                /*
                $regCouponIds = Configure::parentRegCoupon();
                if ($regCouponIds) {
                    foreach ($regCouponIds as $couponId) {
                        UserCoupon::sendToUser($couponId, $user->parent_id);
                    }
                }
                */
                //$parentUser = User::find($user->parent_id);
                //Team::createdTeam($user, $parentUser);
            }


            DB::commit();
            $response = [
                'token'     => (new Token())->generate($user->id, [
                    'id'        => $user->id,
                    'mobile'    => $user->mobile,
                    'open_code' => $user->open_code,
                ]),
                'open_code' => $user->open_code,
                'open_id'   => $user->open_id,
                'mobile' => $user->mobile
            ];


            return success($response);
        }catch (\Exception $e){
            Log::error($e);
            DB::rollBack();
            return fail(500,"系统错误");
        }
    }

    //用户登录(密码和验证码)
    public static function userLogin(array $param){
        try {
            //判断用户登录方式
            if ($param['password']) {
                //查询用户信息
                $userData = User::where("mobile",$param['mobile'])->first();
                if (!$userData)return fail(1014,"用户未注册");
                if ($userData['cancel']==1)return fail(1026,"该账号已被注销");
                Log::info($userData['password']);
                //判断密码是否正确
                if (strtolower($userData['password'])!=$param['password'])return fail(1008,"账号或密码错误");
            }else{
                //验证验证码是否正确
                if (!Sms::validation($param['mobile'],$param['smsCode'])){
                    $errorData = self::errorLogRecord($param['mobile'],$param["ip"]);
                    return fail(1006,$errorData);
                }
                //查询用户
                $userData = User::where("mobile",$param["mobile"])->first();
                if (!$userData)return fail(1014,"用户不存在");
                if ($userData['cancel']==1)return fail(1026,"该账号已被注销");
            }
            //执行修改数据
            $updateValue = [
                'open_id'=>$param['openid'],
                "client_ip"=>$param['ip']
            ];
            $param['platform'] && $updateValue['app_platform'] = $param['platform'];
            $param['android_token'] && $updateValue['android_token'] = $param['android_token'];
            $param['ios_token'] && $updateValue['ios_token'] = $param['ios_token'];
            $param['channel'] && $updateValue['app_channel'] = $param['channel'];
            $param['version'] && $updateValue['app_version'] = $param['version'];
            $param['device_id'] && $updateValue["device_code"] = $param['device_id'];
            (new User())->query()->where("id",$userData['id'])->update($updateValue);

            //写入登陆日志
            $insertValue = ["user_id"=>$userData->id,"mobile"=>$userData->mobile,"ip"=>$param['ip'],"login_date"=>Carbon::now(),"created_at"=>Carbon::now()];
            (new LoginLog())->query()->insert($insertValue);

            //返回数据
            return success([
                'token'     =>(new Token())->generate($userData->id, [
                    'id'        => $userData->id,
                    'mobile'    => $userData->mobile,
                    'open_code' => $userData->open_code,
                ]),
                'open_code' => $userData->open_code,
                'open_id'   => $userData->open_id,
                'mobile' => $userData->mobile
            ]);
            //执行
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    //用户登录微信
    public static function wxLogin(array $param){
        try {
            //执行修改数据
            $updateValue = ['app_platform'=>$param['platform'],'android_token'=>$param['android_token'],'ios_token'=>$param['ios_token'],'app_channel'=>$param['channel'],'app_version'=>$param['version'],"device_code"=>$param['device_id'],"client_ip"=>$param['ip']];
            if(array_key_exists('open_id',$param)){
                $updateValue['open_id'] = $param['open_id'];
            }
            (new User())->query()->where("id",$param['id'])->update($updateValue);

            //写入登陆日志
            $insertValue = ["user_id"=>$param['id'],"openid"=>$param['open_id'],"ip"=>$param['ip'],"login_date"=>Carbon::now(),"created_at"=>Carbon::now()];
            (new LoginLog())->query()->insert($insertValue);

            //返回数据
            return success([
                'token'     =>(new Token())->generate($param['id'], [
                    'id'        => $param['id'],
                    'mobile'    => $param['mobile'],
                    'open_code' => $param['open_code'],
                ]),
                'open_code' => $param['open_code'],
                'open_id'   => $param['open_id'],
                'mobile' => $param['mobile']
            ]);
            //执行
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    //获取unionid
    public static function getUnionid($openid,$access_token){
        try{
            //定义请求地址
            $host = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
            //拉起请求
            $client = new Client();
            $response = $client->request("GET",$host,["verify"=>false]);
            if($response->getStatusCode()==200) {
                //解析返回值
                $data = json_decode($response->getBody()->getContents(), true);
                Log::info('----------------------------------------------');
                Log::info($data);
            }else{
                return self::fail(500,"系统错误");
            }
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    //错误日志记录
    public static function errorLogRecord($mobile,$ip){
        $logData = ErrorLog::where("mobile",$mobile)->where("ip",$ip)->orderBy("id","desc")->first();
        if ($logData && $logData->num<5){
            //数量加一
            $logData->num = $logData->num+1;
            $logData->error_date = Carbon::now();
            $logData->save();
            $differChange = 5-$logData->num;
            return "您还有{$differChange}次机会";
        }elseif($logData && $logData->num>=5){
            //时间差 = 当前时间-上次最后时间
            $differ = time()-strtotime($logData->error_date);
            if ($differ>3600){
                //执行添加
                $log = new ErrorLog();
                $log->mobile = $mobile;
                $log->ip = $ip;
                $log->num = 1;
                $log->error_date = Carbon::now();
                $log->save();
                return '您还有4次机会';
            }else{
                return "您已使用该号码超过5次,请于1小时候重新注册";
            }
        }else{
            //执行添加
            $log = new ErrorLog();
            $log->mobile = $mobile;
            $log->ip = $ip;
            $log->num = 1;
            $log->error_date = Carbon::now();
            $log->save();
            return '非法请求,您还有4次机会';
        }
    }

    //找回密码
    public static function findPassword($mobile,$password){
        try{
            $userData = (new User())->query()->where("mobile",$mobile)->update(["password"=>md5($password)]);
            if (!$userData)return fail(1010);
            return success();
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    //个人中心
    public static function userCenter($userId){
        try{
            //查询用户
            $user = User::find($userId);
            if (!$user)return fail(1014,"用户不存在");
            //最近充值
            $rechargeNowDetail = RechargeOrder::where("user_id",$userId)->where('status','>=',1)->orderBy('id','desc')->select("recharge_amount")->first();
            if ($rechargeNowDetail)
                $prevMoney = "¥".$rechargeNowDetail->recharge_amount;
            else
                $prevMoney = "¥0.00";
            //下次充值

            $rechargeNextDetail = RechargeOrderDetail::where("user_id",$userId)->where("result_status",0)->whereDate("pay_at",">",Carbon::now())->orderBy('pay_at','asc')->select("pay_at","amount")->first();
            if ($rechargeNextDetail){
                $nextRechargeDate= explode(' ',$rechargeNextDetail->pay_at)[0];
                $nextMoney = "¥".$rechargeNextDetail->amount;
            }else{
                $nextRechargeDate = "暂无";
                $nextMoney = "¥0.00";
            }
            //头像
            $avatar = $user->avatar;
            //我拥有的优惠券张数
            $couponNum = UserCoupon::where("user_id",$userId)->where(function ($query){
                $query->where("status",1)->whereDate('finished_at','>=',date('Y-m-d H:i:s',time()));
            })->count();
            //解析昵称
            $nickname = $user->nickname;
            if (!is_null(json_decode($nickname))){
                $nickname = json_decode($nickname);
            }
            //重组数组
            $userArray = ["avatar"=>$avatar,"nickname"=>$nickname,"open_code"=>$user->open_code,"open_id"=>$user->open_id,"mobile"=>$user->mobile,"unionid"=>$user->unionid,"prev_recharge_amount"=>$prevMoney,"next_recharge_date"=>$nextRechargeDate,"next_recharge_amount"=>$nextMoney,"coupon"=>$couponNum,"phone"=>$user->mobile];
            return success($userArray);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    //意见反馈
    public static function feedBack($userId,$title,$content,$mobile){
        try {
            $back = new Feedback();
            $back->user_id = $userId;
            $back->title = $title;
            $back->content = $content;
            $back->mobile = $mobile;
            $back->save();
            return success();
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统异常");
        }
    }

    //用户车辆信息
    public static function userCarIsMethod($userId,$bundleId){
        try{
            //我的车辆信息
            $carData = UserCar::where("user_id",$userId)->orderBy('id','desc')->select("id","plate_number","car_model","vin","engine_number","mobile")->get();
            if (count($carData)>0){
                return success(['car'=>$carData]);
            }else{
                return success(['car'=>[]]);
            }
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    //添加车辆
    public static function userCarAdd($userId,$mobile,$plateNumber,$carModel,$vin,$engineNumber){
        try{
            //查询车辆信息
            $carData = UserCar::where("user_id",$userId)->first();
            if ($carData){
                $carData->plate_number = $plateNumber;
                $carData->car_model = $carModel;
                $carData->vin = $vin;
                $carData->engine_number = $engineNumber;
                $carData->mobile = $mobile;
                $carData->save();
            }else{
                $car = new UserCar();
                $car->user_id = $userId;
                $car->plate_number = $plateNumber;
                $car->car_model = $carModel;
                $car->vin = $vin;
                $car->engine_number = $engineNumber;
                $car->mobile = $mobile;
                $car->save();
            }
            return self::lawbreaking($userId,$plateNumber,$carModel,$vin,$engineNumber);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    //违章查询
    public static function lawbreaking($userId,$plateNumber,$carModel,$vin,$engineNumber){
        try{
            $md5Str = md5("WZ_{$userId}_{$plateNumber}_{$carModel}_{$engineNumber}");
            //判断缓存是否存在
            if (Cache::has($md5Str)){
                return success(Cache::get($md5Str)['result']);
            }
            //截取车牌前两位
            $str = mb_substr($plateNumber,0,2);
            $plate = urlencode($str);
            //定义appKey
            $appKey = "300f7edb76b93cf1ad4edee7a75a5de6";
            //定义请求地址
            $host = "http://v.juhe.cn/sweizhang/carPre.php?key={$appKey}&hphm={$plate}";
            //拉起请求
            $client = new Client();
            $response = $client->request("GET",$host,["verify"=>false]);
            if($response->getStatusCode()!=200) return fail(1006,"请求失败");
            //解析返回值
            $data =  json_decode($response->getBody()->getContents(), true);
            $mobelNUm = '';
            if ($carModel=='小型车'){
                $mobelNUm = 02;
            }
            if($carModel=='大型车'){
                $mobelNUm = 01;
            }
            if($carModel=='新能源小型车'){
                $mobelNUm = 52;
            }
            if ($carModel=='新能源大型车'){
                $mobelNUm = 51;
            }
            //定义请求地址
            $hosts = "http://v.juhe.cn/sweizhang/query?city={$data['result']['city_code']}&hphm={$plateNumber}&hpzl={$mobelNUm}&classno={$vin}&engineno={$engineNumber}&key={$appKey}";
            $response = $client->request("GET",$hosts,["verify"=>false]);
            if($response->getStatusCode()!=200) return fail(1006,"请求失败");
            //解析返回值
            $jsonData =  json_decode($response->getBody()->getContents(), true);
            //计算剩余分钟
            $hour = date('H');
            $min =  date('m');
            $minutes = (60*24)-($hour*60+$min);
            //写入缓存
            Cache::put($md5Str,$jsonData,$minutes);
            return success($jsonData['result']);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    //今日油价
    public static function todayOilPrice($province){
        try{
            //查询今日缓存
            $cacheName = "YJ_".date('Ymd');
            if (Cache::has($cacheName)){
                $data = Cache::get($cacheName);
            }else {
                //定义key
                $appKey = "0649ca360c64776bf839e26315a00340";
                //定义host
                $host = "http://apis.juhe.cn/cnoil/oil_city?key={$appKey}";
                //发起请求
                $client = new Client();
                $response = $client->request("GET", $host, ["verify" => false]);
                if ($response->getStatusCode() != 200) return fail(1006, "请求失败");
                $data = json_decode($response->getBody()->getContents(), true);
                //计算时间
                $minutes = (60 * 24) - (date('H') * 60 - date('m'));
                //写入缓存
                Cache::put($cacheName, $data, $minutes);
            }
            //切割最后一个字符串
            $str = mb_substr($province,-1);
            if ($str=='省' || $str=='市'){
                $city = str_replace($str,'',$province);
            }elseif ($province=='新疆维吾尔族自治区'){
                $city = '新疆';
            }elseif ($province=='内蒙古自治区'){
                $city = '内蒙古';
            }elseif ($province=='广西壮族自治区'){
                $city = '广西';
            }elseif ($province=='西藏自治区'){
                $city = '西藏';
            }elseif ($province=='宁夏回族自治区'){
                $city = '宁夏';
            }elseif ($province=='香港特别行政区'){
                $city = '香港';
            }elseif($province=='澳门特别行政区'){
                $city = '澳门';
            }else{
                $city = $province;
            }
            $array = [];
            foreach ($data['result'] as $k=>$v){
                if ($v['city']==$city){
                    $array = [
                        0=>['key' => '0#柴油', 'value' => "{$v['0h']}元/升"],
                        1=>['key' => '92#汽油', 'value' => "{$v['92h']}元/升"],
                        2=>['key' => '95#汽油', 'value' => "{$v['95h']}元/升"],
                        3=>['key' => '98#汽油', 'value' => "{$v['98h']}元/升"]
                    ];
                }
            }
            return success($array);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统异常");
        }
    }

    //删除车辆
    public static function userCarDelete($id){
        $car = UserCar::find($id);
        if (!$car)return fail(1014,"车辆信息不存在");
        return $car->delete();
    }
}